package cn.com.se.多线程.forkjoin;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @Description TODO
 * @Author:hu.rl
 * @Date:2019-05-30 18:16
 * @Version 1.0
 **/
public class CountTask extends RecursiveTask<Map> {
    private volatile static int count = 0;
    private int start;
    private int end;
    private static Map<String, String> params = new ConcurrentHashMap<String, String>();

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public static final int threadhold = 2;

    @Override
    protected Map compute() {
        Map result = new HashMap();
        System.out.println("开启了一条线程单独干: " + count++);
        // 如果任务足够小, 就直接执行
        boolean canCompute = (end - start) <= threadhold;
        if (canCompute) {
            //任务大于阈值, 分裂为2个任务
            int middle = (start + end) / 2;
            CountTask countTask1 = new CountTask(start, middle);
            CountTask countTask2 = new CountTask(middle + 1, end);
            // 开启线程
            invokeAll(countTask1, countTask2);

            Map<String, String> map1 = countTask1.join();
            Map<String, String> map2 = countTask2.join();
            result.putAll(map1);
            result.putAll(map2);
        }
        return result;
    }


    // 测试
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CountTask.params.put("1","aaaaaaaaa");
        CountTask.params.put("2","bbbb");
        CountTask.params.put("3","cccc");
        CountTask.params.put("4","ddd");
        CountTask.params.put("5","fff");
        CountTask.params.put("6","sss");
        CountTask.params.put("7","asd");
        CountTask.params.put("8","asd");
        CountTask.params.put("9","adads");
        CountTask.params.put("10","asda");

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        CountTask countTask = new CountTask(1, CountTask.params.size());
        ForkJoinTask<Map> result = forkJoinPool.submit(countTask);

        System.out.println(result.get());
    }
}
